import json
from flask import request, render_template
import time
import os
import base64
from service.handle_analysis_sign import AnalysisSign
from service.industry_product_data import IndustryProduct


def register(app, web_path, upload_file, jsonrpc, db_addr, db_port, db_name):
    analysis_sign = AnalysisSign(db_addr, db_port, db_name)
    industry_product = IndustryProduct(db_addr, db_port, db_name)
    @app.route('/upload', methods=['POST', 'GET'])
    def upload():
        result = {}
        if request.method == 'POST':
            f = request.files['file']
            upload_path = upload_file + '\\'+str(int(time.time()))  # 以时间戳命名文件
            file_path = os.path.join(web_path, upload_path).replace('\\', '/')
            if not os.path.exists(file_path):  # 不存在改目录则会自动创建
                os.makedirs(file_path)
            # 保存文件
            save_path = os.path.join(file_path, f.filename).replace(
                '\\', '/')  # windows下路径要转化
            f.save(save_path)
            # 拼接文件url地址
            result = {'code': 200, 'desc': '上传成功', }
            result['url'] = os.path.join(
                upload_path, f.filename).replace('\\', '/')
        return json.dumps(result, ensure_ascii=False)

    @jsonrpc.method('ICompanyTemplateSignService.upload_rc_code')
    def upload_rc_code_service(handle_code, base64_str):
        time_id = str(int(time.time()))
        upload_path = upload_file + '\\'+time_id  # 以时间戳命名文件
        file_path = os.path.join(web_path, upload_path).replace('\\', '/')
        if not os.path.exists(file_path):  # 不存在改目录则会自动创建
            os.makedirs(file_path)
        # 保存文件
        save_path = os.path.join(file_path, time_id).replace(
            '\\', '/')  # windows下路径要转化
        img = base64.b64decode(base64_str.replace(
            'data:image/png;base64,', ''))
        file = open(save_path+'.png', 'wb')
        file.write(img)
        file.close()
        # 拼接文件url地址
        result = {'code': 200, 'desc': '上传成功', }
        result['url'] = os.path.join(
            upload_path, time_id+'.png').replace('\\', '/')
        return result

    @app.route('/product-sign-py/<path:handleCode>', methods=['POST', 'GET'])
    def Index(handleCode):
        def change_structure(name_field,data):
            map_ret = {}
            if data:
                for x in data :
                    map_ret[str(x["id"])] = x[name_field];        
                    # map_ret.set(row.id + '', row[name_field]);        
            return map_ret; 

        industry_list = industry_product.cal_get_industry_list()
        product_type_list = industry_product.cal_get_product_type_list()
        industry_map = change_structure('industry_name',industry_list["result"])
        product_map =  change_structure('product_type_name',product_type_list["result"])
        
        res = analysis_sign.cal_analysis_sign(handleCode)

        exitItem = ["company_handle_code", "category_handle_code",
                    "company_handle_name", "category_handle_name", "rc_code", "handle_type"]

        singleArray = []
        singleHead = {}
        categoryArray = []
        categoryHead = {}
        companyArray = []
        companyHead = {}

        for item in res["attribute"]:
            if item['sign_key'] == 'industry_type':
                item['sign_value'] = industry_map[item['sign_value']]
            if item['sign_key'] == 'product_type':
                item['sign_value'] = product_map[item['sign_value']]
            if item["sign_key"] in exitItem:
                continue
            if item["index"] and item["index"] > 99 and item["index"] < 200:
                if item["sign_key"] == 'handle_name' or item["sign_key"] == 'handle_code' or item["sign_key"] == 'category_picture':
                    categoryHead[item["sign_key"]] = item["sign_value"]
                else:
                    categoryArray.append(item)
            elif item["index"] and item["index"] < 300 and item["index"] > 199:
                if item["sign_key"] == 'handle_name' or item["sign_key"] == 'handle_code' or item["sign_key"] == "product_picture":
                    singleHead[item["sign_key"]] = item["sign_value"]
                else:
                    singleArray.append(item)
            else:
                if item["sign_key"] == 'handle_name' or item["sign_key"] == 'handle_code' or item["sign_key"] == "company_picture":
                    companyHead[item["sign_key"]] = item["sign_value"]
                else:
                    companyArray.append(item)

        # 判断自定义属性是否为空
        def is_empty_custom_attr(arr):
            if "custom_attribute" in arr:
                if len(arr["custom_attribute"]):
                    return True
                else:
                    return False
            else:
                return False

        singleHeadImg = ("product_picture" in singleHead)
        companyHeadImg = ("company_picture" in companyHead)
        categoryHeadImg = ("category_picture" in categoryHead)

        return render_template('product-sign-py.html',
                                handle_code=res["handle_code"],
                                handle_name=res["handle_name"],
                                #
                                singleArray=singleArray,
                                singleArrayLen=len(singleArray),
                                singleHead=singleHead,
                                singleHeadImg=singleHeadImg,
                                #
                                companyArray=companyArray,
                                companyArrayLen=len(companyArray),
                                companyHead=companyHead,
                                companyHeadImg=companyHeadImg,
                                #        
                                categoryArray=categoryArray,
                                categoryArrayLen=len(categoryArray),
                                categoryHead=categoryHead,
                                categoryHeadImg=categoryHeadImg,
                                )
